package com.leyou.item.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.dto.BrandDTO;
import com.leyou.common.dto.PageDTO;
import com.leyou.item.entity.Brand;
import com.leyou.item.entity.CategoryBrand;
import com.leyou.item.mapper.BrandMapper;
import com.leyou.item.service.BrandService;
import com.leyou.item.service.CategoryBrandService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class BrandServiceImpl extends ServiceImpl<BrandMapper, Brand> implements BrandService {

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryBrandService categoryBrandService;

    @Override
    public PageDTO<BrandDTO> queryByPage(Integer page, Integer rows, String key) {
        Page<Brand> infor = new Page<>(page, rows);
        boolean isKeyExists = StringUtils.isNoneBlank(key);
        // 4.如果key存在，添加like和eq的查询条件，否则不添加
        query().like(isKeyExists, "name", key)
                .or()
                .eq(isKeyExists, "letter", key)
                .page(infor);

        List<Brand> list = infor.getRecords();
        return new PageDTO<>(infor.getTotal(), infor.getPages(), BrandDTO.convertEntityList(list));
    }

    @Override
    public void addOrUpdate(BrandDTO brandDTO) {
        Brand brand = brandDTO.toEntity(Brand.class);
        brandService.saveOrUpdate(brand);
        Long ids = brandDTO.getId();
        if(ids != null){
            boolean remove = categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                    .eq("brand_id",ids));
        }

        List<CategoryBrand> list = brandDTO.getCategoryIds().stream()
                .map(id -> CategoryBrand.of(id, brand.getId()))
                .collect(Collectors.toList());
        categoryBrandService.saveBatch(list);
    }

    @Override
    public List<String> getBrands() {
        return brandService.getBrands();
    }


    /**
     * 根据id删除品牌
     * @param id
     */
    public void deleteBrandById(Long id) {
        if (id != null ){
            brandService.removeById(id);
           categoryBrandService.remove(new QueryWrapper<CategoryBrand>()
                    .eq("brand_id",id));

        }
    }
}
